package com.silverbox.sweeporder.controller.index;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.silverbox.shopper.service.info.ShopperInfoService;
import com.silverbox.sweeporder.controller.index.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.StringUtils;
import com.silverbox.shopper.entity.ThirdUserInfo;
import com.silverbox.shopper.entity.extend.ShopperActivities;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.controller.index.entryvo.SavePeopleNumVO;
import com.silverbox.sweeporder.controller.index.entryvo.ShowPeopleNumberVO;
import com.silverbox.sweeporder.service.index.IndexService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 点餐首页接口集合 商品（菜品）获取 热卖商品 活动 套餐
 * 
 * @author YTGHTGHS
 * @date 2017年12月3日
 * @description
 */
@Controller
@RequestMapping("index")
@Api(tags={"首页接口"})
public class IndexController {

	private static Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private IndexService indexService;

	@Autowired
	private ShopperInfoService shopperInfoService;
	
	@Value("${server.url}")
	private String serverUrl;
	
	@Value("${receiveRedEvenlope}")
	private Integer receiveRedEvenlope;
	
	
	@RequestMapping(value = "getShopperInfo", method = RequestMethod.GET)
	@ResponseBody 
	@ApiOperation(value = "店铺信息、桌台信息、配置信息")
	public CoreResponse<ShopperInfoVO> getShopperInfo(HttpSession session,
			@RequestParam(required = true) Integer storeId, @RequestParam(required = false) Integer tableInfoId,
			@RequestParam(required = true) String buyerId,@RequestParam(required = false) Integer clientOrderMode) {
		//定义返回对象
		CoreResponse<ShopperInfoVO> res = new CoreResponse<ShopperInfoVO> ();
		if(storeId == null || StringUtils.isEmpty(buyerId)){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("参数异常,请检查参数!");
			return res;
		}
		res = indexService.getShopperInfoService(storeId,tableInfoId,buyerId,clientOrderMode);
		return res;
	}
	
	@RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
	@ResponseBody 
	@ApiOperation(value = "获取用户信息(可调用)")
	public CoreResponse<UserInfoVO> getUserInfo(HttpSession session, @RequestParam(required = true) String buyerId,
			@RequestParam(required = false) Integer authMode) {
		//定义返回对象
		CoreResponse<UserInfoVO> res = new CoreResponse<UserInfoVO>();
		if (StringUtils.isEmpty(buyerId)) {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("请检查参数，参数异常");
			return res;
		}
		// 判断登录模式 1支付宝  2微信
		if (!new Integer(2).equals(authMode)) {
			authMode = 1;
		}
		// 获取第三方用户信息，暂时只有支付宝
		ThirdUserInfo thirdUserInfo = indexService.getThirdUserInfoBuyerId(buyerId, authMode);
		if (thirdUserInfo == null) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("获取第三方用户信息异常");
			return res;
		}
		
		// 获取会员信息
		MemberInfoVO memberInfo = indexService.getMemberUserInfo(buyerId);
		if(memberInfo==null){
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("获取会员信息失败");
			return res;
		}
		ThirdUserInfoVO thirdUserInfoVO = new ThirdUserInfoVO();
		BeanUtils.copyProperties(thirdUserInfo, thirdUserInfoVO);
		UserInfoVO userInfo = new UserInfoVO();
		userInfo.setMemberInfo(memberInfo);
		userInfo.setThirdUserInfo(thirdUserInfoVO);
		res.setData(userInfo);
		return res;
	}
	
	@RequestMapping(value = "getPageConfig", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "店铺装修接口(josn数据格式)")
	public CoreResponse<Object> getPageConfig(@RequestParam(required = true) Integer storeId,
			@RequestParam(required = true) Integer shopperId,@RequestParam(required=true) Integer clientOrderMode) {
		CoreResponse<Object> res = new CoreResponse<Object>();
		if(shopperId==null || storeId==null || clientOrderMode==null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常！请检查参数");
			return  res;
		}
		int decorationType = 0;
		//在线订单类型
		if((Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue()).equals(clientOrderMode)
        || (Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue()).equals(clientOrderMode)){
			decorationType = 1;
		}
		//查询店铺是否开启扫码下单店铺装修配置
		Integer renovationShopper = indexService.findByPropName(shopperId, "IS_OPEN_SWEEPORDER_DECORATION");
		Map<String, Object> renovationMap = new HashMap<>();
		//如果开启店铺装修
		if (new Integer(1).equals(renovationShopper)) {
			List<Long> list = indexService.getShopperRenovationByStoreId(storeId,decorationType);
			// 如果没有绑定店铺则查询默认模板
			if (CollectionUtils.isEmpty(list)) {
				renovationMap = indexService.getShopperRenovationDefaultConfig(decorationType);
			} else {
				JSONObject json = indexService.getShopperRenovationByShopperId(list.get(0),decorationType);
				// 如果绑定的默认模板查询不存在，则查询默认模板
				if (json == null) {
					renovationMap = indexService.getShopperRenovationDefaultConfig(decorationType);
				} else {
					res.setData(json);
					return res;
				}
			}
		}else{
			renovationMap = indexService.getShopperRenovationDefaultConfig(decorationType);
		}
		res.setData(renovationMap);
		return res;
	}

	@RequestMapping(value = "getActivityList", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取店铺活动(可调用)")
	public CoreResponse<List<ShopperActivities>> getActivityList(HttpSession session, HttpServletRequest request,@RequestParam(required=true) String shopId) {
		// 返回前端参数
		CoreResponse<List<ShopperActivities>> res = new CoreResponse<List<ShopperActivities>>();
		// 获取店铺活动
		List<ShopperActivities> shopperActivities = null;
		if (!StringUtils.isEmpty(shopId)) {
			shopperActivities = indexService.getShopperActivityList(shopId);
		}
		res.setData(shopperActivities);
		return res;
	}

	@RequestMapping(value = "getShopperCallService", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "（店铺必须开启呼叫服务）获取店铺开启呼叫服务信息(在线订单没有呼叫服务，不需要调)")
	public CoreResponse<CallServiceInfoCVO> getShopperCallService(HttpSession session,
			HttpServletRequest request,@RequestParam(required=true) Integer storeId,@RequestParam(required=false)Integer tableInfoId) {
		// 返回前端参数  获取店铺呼叫服务
		CoreResponse<CallServiceInfoCVO> res = new CoreResponse<CallServiceInfoCVO>();
		if(storeId==null){
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setSubMsg("参数异常请检查参数");
			return res;
		}
		res = indexService.getShopperCallService(storeId,tableInfoId);
		
		return res;
	}
	
//	@RequestMapping(value = "getReceiveRedEvenlope", method = RequestMethod.GET)
//	@ResponseBody
//	@ApiOperation(value = "领取红包（可调用）")
//	public CoreResponse<Map<String, Object>> getReceiveRedEvenlope(HttpSession session) {
//		CoreResponse<Map<String, Object>> res = new CoreResponse<Map<String, Object>>();
//		Map<String, Object> RedEvenlopeMap = new HashMap<String, Object>();
//
//		// 判断是否开启领取红包
//		if (!new Integer(1).equals(receiveRedEvenlope)) {
//			RedEvenlopeMap.put("status", new Integer(-2)); // -3领取红包异常，-2系统限制不领红包，-1系统异常，0未领取过红包，1成功领取红包，2已领取过红包或领取失败，
//			res.setData(RedEvenlopeMap);
//			res.setStatusInfo(StatusInfo.NORESOURCE);
//			res.setMsg("系统限制不领红包");
//			return res;
//		}
//		res = indexService.getReceiveRedEvenlope(buyerId.toString());
//		return res;
//	}
	
	@RequestMapping(value="saveEatPeopleNumber",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "保存就餐人数")
	public CoreResponse<Map<String,Object>> saveEatPeopleNum(HttpSession session,
			@RequestBody(required = true) SavePeopleNumVO savePeopleNum) {

		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		if (savePeopleNum == null || savePeopleNum.getStoreId() == null || savePeopleNum.getShopperId() == null
				|| savePeopleNum.getPeopleNumber() == null || StringUtils.isEmpty(savePeopleNum.getBuyerId())) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("参数异常");
			return res;
		}
		res = indexService.saveEatPeopleNum(savePeopleNum);
		return res;
	}
	
//	@RequestMapping(value="getShopperPageConfig",method=RequestMethod.GET)
//	@ResponseBody
//	@ApiOperation(value = "获取店铺装修配置信息（封装成对象数据格式）")
//	public CoreResponse<DecorationVO> getShopperPageConfig(@RequestParam(required = true) Integer storeId,
//			@RequestParam(required = true) Integer shopperId) {
//		CoreResponse<DecorationVO> res = new CoreResponse<DecorationVO>();
//		if(storeId == null || shopperId ==null){
//			res.setStatusInfo(StatusInfo.ERROR_40002);
//			res.setSubMsg("参数异常!请检查参数");
//			return res;
//		}
//		res = indexService.getShopperDecorationInfo(storeId,shopperId,decorationType);
//		return res;
//	}
	
//	@RequestMapping(value = "getMarketingTrigger", method = RequestMethod.GET)
//	@ResponseBody
//	@ApiOperation(value = "营销抽奖活动触发抽奖")
//	public CoreResponse<AlipayMarketingTriggerVO> getMarketingTrigger(HttpSession session,
//			@RequestParam(required = false) String telNumber, @RequestParam(required = false) Integer source,
//			@RequestParam(required = false) String userId,@RequestParam(required=false) String loginId) {
//		CoreResponse<AlipayMarketingTriggerVO> res = new CoreResponse<AlipayMarketingTriggerVO>();
//		
//		if((StringUtils.isEmpty(userId) && StringUtils.isEmpty(loginId)) && StringUtils.isEmpty(telNumber)){
//			res.setStatusInfo(StatusInfo.ERROR_40002);
//			res.setSubMsg("用户id、用户登录账号、手机号三个至少一个非空");
//			return res;
//		}
//		//如果手机号存在，则进行校验
//		if(StringUtils.isNotEmpty(telNumber)){
//			if(!Utils.isChinaPhoneLegal(telNumber)){
//				res.setStatusInfo(StatusInfo.ERROR_40002);
//				res.setSubMsg("手机号格式有误");
//				return res;
//			}
//		}
//		res = indexService.getMarketingTrigger(telNumber,userId,loginId,source);
//		return res;
//	}
	
	@RequestMapping(value = "getShowPeopleNumber", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取必点菜下是否跟人数关联，如果关联则加菜时不显示人数(在线订单不存在加菜,不需要调用该接口)")
	public CoreResponse<Map<String, Integer>> getShowPeopleNumber(HttpSession session,
			@RequestBody(required = true) ShowPeopleNumberVO showPeopleNumber) {

		CoreResponse<Map<String, Integer>> res = new CoreResponse<Map<String, Integer>>();

		if (StringUtils.isEmpty(showPeopleNumber.getBuyerId()) || showPeopleNumber.getShopperId() == null
				|| showPeopleNumber.getStoreId() == null) {
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("参数有误！请检查参数");
			return res;
		}
		Map<String, Integer> showMap = indexService.getShowPeopleNumber(showPeopleNumber);
		res.setData(showMap);
		return res;
	}
	
	
	/**
	 * 小程序二维码解析
	 * @param request
	 * @param storeId
	 * @param thirdUserInfoId
	 * @param mode
	 * @param url
	 * @return
	 */
	@RequestMapping(value = "getAnalyzeQrcodePath", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取小程序内扫描二维码获取跳转地址")
	public CoreResponse<QrcodeVO> getAnalyzeQrcodePath(HttpServletRequest request,
			@RequestParam(required = true) Integer storeId, @RequestParam(required = true) Long thirdUserInfoId,
			@RequestParam(required = true) Integer mode, @RequestParam(required = true) String url) {
		CoreResponse<QrcodeVO> res = new CoreResponse<QrcodeVO>();	
		if(StringUtils.isEmpty(url) || storeId==null || thirdUserInfoId==null || mode==null){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			return res;	
		}
		res = indexService.getAnalyzeQrcodePath(storeId,thirdUserInfoId,url,mode);
		return res;
	}

	@RequestMapping(value="getNearestStoreAddressInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = " 获取距离当前位置最近的店铺信息 ")
	public CoreResponse<List<ShopAddressInfoVO>> getNearestStoreAddressInfo(HttpServletRequest request,
            HttpSession session,@RequestParam Integer shopperId,@RequestParam Integer storeId,@RequestParam String cityCode,
             @RequestParam String longitude,@RequestParam String latitude){
        CoreResponse<List<ShopAddressInfoVO>> res=new CoreResponse<>();
	    if (storeId==null && StringUtils.isEmpty(cityCode) && StringUtils.isEmpty(longitude) && StringUtils.isEmpty(latitude)){
	        res.setStatusInfo(StatusInfo.ERROR_40001);
	        return res;
        }
        List<ShopAddressInfoVO> shopAddressInfoVOList=shopperInfoService.getNearestStoreAddressInfo(shopperId,storeId,cityCode,longitude,latitude);
	    if (CollectionUtils.isEmpty(shopAddressInfoVOList)){
            res.setMsg("当前城市没有发现相关店铺");
            return res;
        }
	    res.setData(shopAddressInfoVOList);
	    return res;
    }
	
	@RequestMapping(value = "getAppointmentTime", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取预约时间")
	public CoreResponse<AppointmentTimeVO> getAppointmentTime(HttpSession session, HttpServletRequest request, //加上其他参数
			@RequestParam(required = true) Integer storeId,@RequestParam(required = true) Integer shopperId,@RequestParam(required = false) String date){
		CoreResponse<AppointmentTimeVO> res = new CoreResponse<AppointmentTimeVO>();
		if(storeId == null || shopperId == null){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("获取预约时间失败,缺少必选参数");
			return res;
		}
		res = indexService.getAppointmentTime(storeId,shopperId,date);
		return res;
	}

	@RequestMapping(value = "appointmentVerification", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "预约下单验证")
	public CoreResponse<String> appointmentVerification(HttpSession session, HttpServletRequest request, //加上其他参数
			@RequestBody(required = true) ReserveBasicInfoVO reserveBasicInfoVO,@RequestParam(required = false) String date){
		CoreResponse<String> res = new CoreResponse<String>();
		if(reserveBasicInfoVO.getStoreId() == null || reserveBasicInfoVO.getShopperId() == null){
			res.setStatusInfo(StatusInfo.ERROR_40001);
			res.setSubMsg("获取预约时间失败,缺少必选参数");
			return res;
		}
		res = indexService.appointmentVerification(reserveBasicInfoVO,date);
		return res;
	}

}
